package com.freesky.biz.citic.utils;

import org.bouncycastle.util.encoders.Base64;

import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;

public class TransProcessUtils {

    public static String encryptBusiness(String business, String publicKey) throws Exception {
        String businessB64Str = Base64.toBase64String(business.getBytes(StandardCharsets.UTF_8));
        String sm4Key = SMUtils.genSm4Key();
        String encryptedBusiness = SMUtils.sm4Encrypt(sm4Key, businessB64Str);
        String encryptedSm4Key = SMUtils.sm2Encrypt(publicKey, sm4Key);
        return encryptedBusiness + "@@" + encryptedSm4Key;
    }

    public static String decryptBusiness(String encryptBody, String privateKey) throws Exception {
        String[] cipherArr = encryptBody.split("@@");
        // 使用SM4KEY加密业务报文后的密文
        String encryptedData = cipherArr[0];
        // 使用SM2公钥对SM4KEY加密后的密文
        String encryptedSm4Key = cipherArr[1];

        //1、使用SM2平台私钥解密SM4KEY后的base64编码的sm4key
        String sm4Key = SMUtils.sm2Decrypt(privateKey, encryptedSm4Key);

        //2、对称密钥SM4KEY解密报文后的base64编码字符串
        String decryptedBusinessB64Str = SMUtils.sm4Decrypt(sm4Key, encryptedData);
        String responseData = new String(Base64.decode(decryptedBusinessB64Str), StandardCharsets.UTF_8);
        return responseData;
    }

    public static String signBusiness(String business, String privateKey) throws Exception {
        byte[] bytes = SMUtils.sm3Hash(business.getBytes(StandardCharsets.UTF_8));
        return SMUtils.sign(bytes, privateKey);
    }

    public static boolean verifyBusiness(String cert, String business, String signData) throws Exception {
        byte[] originBytes = SMUtils.sm3Hash(business.getBytes(StandardCharsets.UTF_8));
        return SMUtils.certVerify(cert, originBytes, signData);
    }

    public static void main(String args[]) throws Exception, InvalidAlgorithmParameterException {
        TransProcessUtils transProcessUtils = new TransProcessUtils();

        System.out.println(TransProcessUtils.encryptBusiness("test",
                "MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAERjku/Kvh2ag4jrd55MDlXaxraxH0qT6G/89U/ahe259ysrEG+BVBgzkkxOqK3Wqv1DZpxaZj/2CAGeFar7Qtqg=="));
    }
}
